package com.lukebang.controller;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.lukebang.dao.InstallIndentDAO;
import com.lukebang.pojo.Good;
import com.lukebang.pojo.Result;
import com.lukebang.service.IGoodService;
import com.lukebang.service.IInstallIndentService;
import com.lukebang.util.JsonUtil;
import com.lukebang.util.redis.JedisPoolUtils;

import redis.clients.jedis.Jedis;

/**
 * 
 * TaskManageController 下午1:14:23 Copyright zhaocj Inc. All Rights reserved.
 * alldios@outlook.com
 *
 */    
@Controller
@RequestMapping("/indent")
public class InstallIndentForController {

	@Resource
	@Qualifier("installIndentSER")
	private IInstallIndentService installIndentSER;
	@Resource
	private IGoodService goodService;
	@Resource
	InstallIndentDAO installIndentDAO;
	private static Logger logger = LogManager.getLogger(InstallIndentForController.class.getName());

	/**
	 * 功能：取消订单
	 * 
	 * @param request
	 * @param mesureIndentId
	 * @return
	 */
	// @RequestMapping("/quitInstallIndent")
	// @ResponseBody
	// public Map<String,Object> quitInstallIndent(HttpServletRequest
	// request,HttpSession session,Integer indentId,Integer type){
	// return installIndentSER.quitIndent(request, session, type, indentId);
	// }
	// 添加安装订单
	@RequestMapping("/addInstall")
	public String install(Model model) {
		model.addAttribute("oneMenu", "newTask");
		model.addAttribute("twoMenu", "install");
		
		return "/cms/newTask/addInstall";
	}

	// 查看我的订单
	@RequestMapping("/installList")
	public String installList(Model model) {
		model.addAttribute("oneMenu", "taskList");
		model.addAttribute("twoMenu", "installList");
		return "/cms/taskList/installList";
	}

	// 查看我的维修订单
	@RequestMapping("/installList/{status}")
	public String measureList(Model model, @PathVariable("status") String status) {
		model.addAttribute("oneMenu", "taskList");
		model.addAttribute("twoMenu", "installList");
		if ("pay".equals(status)) {
			return "/cms/taskList/installList0";
		} else if ("taking".equals(status)) {
			return "/cms/taskList/installList1";
		} else if ("order".equals(status)) {
			return "/cms/taskList/installList2";
		} else if ("move".equals(status)) {
			return "/cms/taskList/installList3";
		} else {
			return "/cms/taskList/installList4";
		}
	}

	/**
	 * 在已有订单中添加商品
	 */
	@RequestMapping("/addGoodsForExistIndent")
	@ResponseBody
	public boolean addGoodsForExistIndent(Integer indentID, Good good, String finishShade, String clothShade,
			String yarnShade, String headShade, HttpServletRequest request, String fakeIndentID, HttpSession session) {
		installIndentSER.insertGoodsThatExistIndent(indentID, good, finishShade, clothShade, yarnShade, headShade,
				request, fakeIndentID, session);
		return true;
	}

	/**
	 * 在redis中为安装订单添加商品和尺寸信息
	 * 
	 * @param indentID
	 * @param good
	 * @param finishShade
	 * @param clothShade
	 * @param yarnShade
	 * @param headShade
	 * @return
	 */
	// 为fakeIndent添加商品信息
	@RequestMapping("/addFakeGoodsForIndent")
	public @ResponseBody boolean addFakeGoodsForIndent(String indentID, Good good, String finishShade,
			String clothShade, String yarnShade, String headShade, HttpServletRequest request, String phone,
			String name, String remark, String installAddress, String province, String city, String country,
			String subscribeTime, Integer isNeedTakeGoods, String pickupPhone, String pickupProvince, String pickupCity,
			String pickupCountry, String pickAddress, String fakeIndentID, HttpSession session) {
		try {
			// 为订单存储数据
			Jedis jedis = JedisPoolUtils.getJedis();
			jedis.select(2);
			// 生成GoodID
			String currentGoodID = 1 + (System.currentTimeMillis() + "").substring(5);
			jedis.lpush(indentID, currentGoodID.toString());
			jedis.expire(indentID, 60 * 50);
			Map<String, String> goodMap = new HashMap<String, String>();
			goodMap.put("currentGood", JsonUtil.toJson(good));
			if (finishShade != null && !("".trim().equals(finishShade))) {
				goodMap.put("finishShade", finishShade);
			}
			if (clothShade != null && !("".trim().equals(clothShade))) {
				goodMap.put("clothShade", clothShade);
			}
			if (yarnShade != null && !("".trim().equals(yarnShade))) {
				goodMap.put("yarnShade", yarnShade);
			}
			if (headShade != null && !("".trim().equals(headShade))) {
				goodMap.put("headShade", headShade);
			}
			String jsonString = JSON.toJSONString(goodMap);
			jedis.set(indentID + "_" + currentGoodID, jsonString);
			jedis.expire(indentID + "_" + currentGoodID, 60 * 50);
			JedisPoolUtils.close(jedis);
			System.out.println("=======" + finishShade + clothShade + yarnShade + headShade + "订单id-【" + indentID + "】,"
					+ fakeIndentID);
			/*
			 * //添加新增商品啦。 installIndentSER.insertNewInstallGoods(request, phone, name,
			 * remark, installAddress, province, city, country, subscribeTime,
			 * isNeedTakeGoods, pickupPhone, pickupProvince, pickupCity, pickupCountry,
			 * pickAddress, fakeIndentID, session);
			 * System.out.println("执行了这句哦 哦哦哦哦哦哦哦哦哦哦哦哦哦哦哦");
			 */
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	@RequestMapping("/good/refreshInstallIndentGoods")
	public @ResponseBody Map<String, Object> refreshInstallIndentGoods(String fakeIndentID, String cityCodeStr) {
		Map<String, Object> retMap = null;
		try {
			retMap = goodService.selectForRefreshInstallIndentGoods(fakeIndentID, cityCodeStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return retMap;
	}

	/**
	 * 从redis中删除商品和尺寸信息
	 * 
	 * @param indentID
	 * @param goodID
	 * @return
	 */
	@RequestMapping("/deleteFakeGood")
	public @ResponseBody boolean deleteFakeGoodsForIndent(String indentID, String goodID) {
		logger.debug("indent:{},goodID:{}", indentID, goodID);
		// 为订单存储数据
		Jedis jedis = JedisPoolUtils.getJedis();
		jedis.select(2);
		jedis.lrem(indentID, 1, goodID);
		JedisPoolUtils.close(jedis);
		return true;
	}

	/**
	 * 从从已添加的商品中删除
	 * 
	 * @param indentID
	 * @param goodID
	 * @return
	 */
	@RequestMapping("/deleteGoods")
	public @ResponseBody boolean deleteGoodsForIndent(Integer indentID, Integer goodID) {
		logger.debug("indent:{},goodID:{},opt:{}", indentID, goodID);
		// 解除goods表中的关系isDeleted
		installIndentDAO.deleteGoods(goodID);
		Map<String, Object> goods_indent = new HashMap<>();
		goods_indent.put("indentID", indentID);
		goods_indent.put("goodID", goodID);
		System.out.println("*******进入删除商品啦啦啦啦阿" + goods_indent);
		installIndentDAO.deleteGoodsAndIndent(goods_indent);
		return true;
	}

	// 删除商品后重新计算价格
	@RequestMapping("/resetCalculateIndent")
	public @ResponseBody void resetCalculateIndent(Integer indentID) {
		logger.debug("indent:{}", indentID);
		System.out.println("进入重新计算价格啦controller======,indentID=" + indentID);
		installIndentSER.resetCalculateIndent(indentID);
	}

	/**
	 * 生成安装订单
	 * 
	 * @param request
	 * @param phone
	 * @param name
	 * @param remark
	 * @param timestamp
	 * @param installAddress
	 * @param province
	 * @param city
	 * @param country
	 * @param subscribeTime
	 * @param isNeedTakeGoods
	 * @param pickupPhone
	 * @param pickupProvince
	 * @param pickupCity
	 * @param pickupCountry
	 * @param pickAddress
	 * @param fakeIndentID
	 * @param session
	 * @return
	 */
	@RequestMapping("/makeInstallIndent")
	public @ResponseBody Result makeInstallIndent(HttpServletRequest request, String phone, String name, String remark,
			String installAddress, String province, String city, String country, String subscribeTime,
			Integer isNeedTakeGoods, String pickupPhone, String pickupProvince, String pickupCity, String pickupCountry,
			String pickAddress, String fakeIndentID, HttpSession session) {
		Result result = new Result();
		try {
			Map<String, Object> indent = installIndentSER.insertInstallIndent(request, phone, name, remark,
					installAddress, province, city, country, subscribeTime, isNeedTakeGoods, pickupPhone,
					pickupProvince, pickupCity, pickupCountry, pickAddress, fakeIndentID, session);
			result.setStatus(0);
			result.setData(indent);
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatus(1);
		}
		return result;
	}

	/**
	 * 根据登录用户和查询条件查询所有的订单信息
	 * 
	 * @param session
	 * @param cuName
	 * @param cuPhone
	 * @param indentID
	 * @param subscribeTimeBegin
	 * @param subscribeTimeEnd
	 * @param beginTimeBegin
	 * @param beginTimeEnd
	 * @param indentStatus
	 * @param offset
	 * @param limit
	 * @param sort
	 * @param order
	 * @return
	 */
	@RequestMapping("/queryInstallIndentByMerchant")
	public @ResponseBody Map<String, Object> queryInstallIndentByMerchant(HttpSession session, String cuName,
			String cuPhone, String indentID, String subscribeTimeBegin, String subscribeTimeEnd, String beginTimeBegin,
			String beginTimeEnd, Integer indentStatus, Integer offset, Integer limit, String sort, String order) {
		// logger.debug("查询参数是，顾客姓名：{}，顾客手机号：{}，订单号：{}，预约时间开始：{}，预约时间结束：{}，下单时间开始：{}。下单时间结束：{}，订单的状态：{}",
		// cuName, cuPhone,
		// indentID, subscribeTimeBegin, subscribeTimeEnd, beginTimeBegin, beginTimeEnd,
		// indentStatus);
		// logger.debug("传入的表格参数是{},{},{},{}", offset, limit, sort, order);
		Map<String, Object> installIndentMap = null;
		try {
			installIndentMap = installIndentSER.selectInstallIndentByMerchant(session, cuName, cuPhone, indentID,
					subscribeTimeBegin, subscribeTimeEnd, beginTimeBegin, beginTimeEnd, indentStatus, offset, limit,
					sort, order);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return installIndentMap;
	}

	/**
	 * 进入到付款modal并且进行付款操作
	 * 
	 * @param request
	 * @param indentID
	 * @param addPrice
	 * @param relievedBao
	 * @param crampetNumber
	 * @param fourClawNumber
	 * @param motorNumber
	 * @param session
	 * @return
	 */
//	@RequestMapping("/payInstallIndent")
//	public String payInstallIndent(HttpServletRequest request, Integer indentID, Double addPrice, Integer relievedBao,
//			Integer crampetNumber, Integer fourClawNumber, Integer motorNumber, HttpSession session) {
//		try {
//
//			System.out.println("进入支付页面--------------");
//			System.out.println("indentID:" + indentID);
//			System.out.println("addPrice:" + addPrice);
//			System.out.println("relievedBao:" + relievedBao);
//			System.out.println("crampetNumber:" + crampetNumber);
//			System.out.println("fourClawNumber:" + fourClawNumber);
//			System.out.println("motorNumber:" + motorNumber);
//			installIndentSER.modifyForPayInstallIndent(request, indentID, addPrice, relievedBao, crampetNumber,
//					fourClawNumber, motorNumber, addPrice, session);
//			return "forward:/cms/alipay/alipayapi.jsp";
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return null;
//	}
}
